const io = require('./io');
const fs = require('fs');
const path = require('path');
const aes = require('./aes');
const dir = path.normalize(path.join(process.env.USERPROFILE, '.mh'));
const ddir = path.resolve(path.normalize(path.join(process.env.USERPROFILE, '.dmh')));
new Promise((resolve, reject) => {
	io.checkPath(dir, (error) => {
		!error ? resolve() : reject();
	})
}).then(
	() => {
		!fs.existsSync(ddir) ? fs.mkdirSync(ddir) : '';
		console.log('start find history');
		let mhs = io.readFileListSync(dir);
		console.log(`find ${mhs.length} file(s)`);
		console.log('start decode');
		mhs.forEach((p) => {
			let realPath = path.resolve(p);
			let res = { date: path.basename(realPath).split('.')[0] };
			io.readFile(realPath, (error, data) => {
				let primary = JSON.parse(data.toString());
				let key = primary.k;
				let iv = primary.i;
				console.log(`get base key successfully: ${key}`);
				let d = aes(key, iv).d;
				console.log('create decoder successfully');
				const date = d(res.date);
				const name = `${new Date(Number(date)).getFullYear()}-${new Date(Number(date)).getMonth() + 1}-${new Date(Number(date)).getDate()}`;
				console.log(`history: ${name}`);
				let msg = primary.msg;
				let dmsg = [];
				console.log(`get encode msg: ${msg}`);
				msg.forEach((msg, index) => {
					console.log(`decoding: ${msg}`);
					dmsg.push(d(msg));
					console.log(`decode: ${dmsg[index]}`);
				})
				fs.createWriteStream(path.resolve(path.join(ddir, name + '.txt')), { flags: 'a' }).end(dmsg.join('\n') + '\n------------------------------------------------------------------\n');
				console.log('finish');
			})
		})
	}
	, () => {
		console.log('no history');
	}
)